<template>
	<view></view>
</template>

<script>
import { getGroupMsg, getPersonMsg } from '@/utils/getMsgHistory.js';
import { getGroup } from '@/utils/polygonInMap';
const linli = uniCloud.importObject('linliChat', { customUI: true });
import onekeylogin from '@/utils/onekeyLongin.js';

import * as msgAction from '@/utils/msgAction.js';

import { getGridCode } from '../../utils/getSurroundingGrids';

export default {
	data() {
		return {
			debug: true
		};
	},

	async onLoad() {
		try {
			await this.start();
		} catch (e) {
			uni.showToast({
				title: '初始化失败',
				icon: 'error'
			});
		}
	},
	methods: {
		getUserTel() {
			return new Promise(async (resolve, reject) => {
				let userTel = '';
				const { model } = uni.getSystemInfoSync();
				if (model === 'BRA-AL00' && this.debug) {
					userTel = '15160169899';
					resolve(userTel);
					return;
				}
				const res = uni.getStorageSync('userTel');
				if (res) {
					userTel = res;
					resolve(userTel);
				} else {
					getApp().globalData.firstLogin = true; //告诉APP是第一次登录，所以在调一键登录时，onshow无须再走showAgain.js
					const result = await onekeylogin();
					if (!result || !result.userTel) {
						return reject(new Error('未获取到用户手机号'));
					}
					userTel = result.userTel;
					uni.setStorageSync('userTel', userTel);
					resolve(userTel);
				}
			});
		},

		getPushId() {
			return new Promise((resolve, reject) => {
				const cid = uni.getStorageSync('pushId');
				if (cid) {
					resolve(cid);
				} else {
					uni.getPushClientId({
						success: (res) => {
							resolve(res.cid);
							uni.setStorageSync('pushId', res.cid);
							console.log('cid', res);
						},

						fail: () => reject(new Error('未获取到推送ID'))
					});
				}
			});
		},

		// 核心逻辑：区分缓存存在/不存在两种场景
		async start() {
			const userTel = uni.getStorageSync('userTel');
			const user = uni.getStorageSync('user');
			const lastLocation = uni.getStorageSync('lastLocation');
			const hasValidCache = Object.keys(user).length > 0 && userTel && Object.keys(lastLocation).length > 0;

			// 1. 缓存存在：同步state并跳转，后续仅执行必要更新
			if (hasValidCache) {
				this.$store.commit('msg/SET_user', user);
				this.$store.commit('msg/SET_stateConfig', user.stateConfig);
				this.$store.commit('msg/SET_location', lastLocation);
				// 立即跳转（不阻塞后续更新）
				uni.redirectTo({ url: '/pages/mainTwo/mainTwo' });

				// 后台执行定位和WS连接更新（使用缓存中的用户信息）
				await this.updateLocationAndWebSocket(user.userTel);
			}

			// 2. 缓存不存在：执行完整初始化流程
			try {
				// 必须获取手机号和推送ID

				const [userTel, pushCid] = await Promise.all([this.getUserTel(), this.getPushId()]);
				const res = await linli.getUserFromDb(userTel, pushCid);//开始注册 
               console.log("用户信息",res);
				if (!res.user?.userId) {
					throw new Error('用户信息不完整');
				}

				// 更新用户信息到Vuex
				this.$store.commit('msg/SET_user', res.user);
				this.$store.commit('msg/SET_stateConfig', res.user.stateConfig);

				// 执行定位和WS连接
				await this.updateLocationAndWebSocket(userTel);

				// 绑定设备
				await getApp().bindDeviceToUser(res.user);

				// 无缓存时跳转
				uni.redirectTo({ url: '/pages/mainTwo/mainTwo' });
			} catch (e) {
				const errorMsg = `初始化失败：${e.message}`;
         		console.error(errorMsg, e);
				uni.showToast({ title: errorMsg, icon: 'none', duration: 3000 });
			}
		},

		// 抽取公共方法：执行定位更新和WebSocket连接（缓存存在/不存在均调用）
		async updateLocationAndWebSocket(userTel) {
			try {
				let location = {};
				const hasLocation = this.$store.state.msg.locationHandler;

				if (hasLocation) {
					location = this.$store.state.msg.location;
				} else {
					location = await this.$store.dispatch('msg/getLocation');
				}

				if (!location) {
					throw new Error('获取定位失败');
				}

				const isWsConnected = await this.$store.dispatch('msg/connectWebSocket', {
					location,
					userTel
				});

				if (!isWsConnected) {
					throw new Error('WebSocket连接失败');
				}
			} catch (e) {}
		}
	}
};
</script>

<style></style>
